package com.nuanshui.heatedloan.fund.integration.pay.execute;

import com.google.common.collect.Maps;
import com.nuanshui.framework.springContext.SpringContextUtil;
import com.nuanshui.heatedloan.fund.integration.form.CancelPayForm;
import com.nuanshui.heatedloan.fund.integration.form.PayForm;
import com.nuanshui.heatedloan.fund.integration.form.RequestPayForm;
import com.nuanshui.heatedloan.fund.integration.pay.bean.PayConfirmHandlerMeta;
import com.nuanshui.heatedloan.fund.integration.pay.execute.sysexecute.AbstractPayExecute;
import com.nuanshui.heatedloan.fund.model.PayResult;

import java.util.HashMap;
import java.util.List;

public class  PayExecuteFacadeImpl implements PayExecuteFacade{


	private PayExecuteRegistrar payExecuteRegistrar = new PayExecuteRegistrar();
	
	private HashMap<String, AbstractPayExecute> payExecuteCache = Maps.newHashMap();
	
	public PayExecuteRegistrar getPayExecuteRegistrar() {
		return payExecuteRegistrar;
	}


	@Override
	public String loadPayNum(RequestPayForm requestPayForm) {
		PayExecute payExecute =  payExecuteRegistrar.getPayExecute(requestPayForm.getPayBizType());
		
		return payExecute.loadPayNum(requestPayForm);
	}

	@Override
	public PayResult executeConfirmPay(PayForm payForm) {
		String key = payForm.getPayType()+"_"+payForm.getPayBizType();
		AbstractPayExecute payExecute =  payExecuteCache.get(key);
		if(payExecute == null) {//支付确认的执行连组装
			payExecute = (AbstractPayExecute) payExecuteRegistrar.getPayExecute(payForm.getPayBizType());
			PayConfirmHandler finalPayConfirmHandler =  payExecuteRegistrar.getFinalPayConfirmHandlers(payForm.getPayBizType());
			PayConfirmHandler temp =null;
			List<PayConfirmHandlerMeta> metas = payExecuteRegistrar.getPayConfirmHandlers();
			for(PayConfirmHandlerMeta payConfirmHandlerMeta :metas) {
				if(payConfirmHandlerMeta.matchs(payForm)) {
					temp = payConfirmHandlerMeta.getPayConfirmHandler();
					temp = SpringContextUtil.getBean(temp.getClass());
					temp.setPayConfirmHandler(finalPayConfirmHandler);
					finalPayConfirmHandler = temp;
				}
			}
			payExecute.setPayConfirmHandler(finalPayConfirmHandler);
			payExecuteCache.put(key, payExecute);
		}
		return payExecute.executeConfirmPay(payForm);
	}

	@Override
	public boolean cancelPay(CancelPayForm payForm) {
         PayExecute payExecute =  payExecuteRegistrar.getPayExecute("");
		
		return payExecute.cancelPay(payForm);
	}

}
